package com.groupbuying.store.service.impl;

//import com.groupbuying.common.baseutils.baseframework4plugins.message.MessageHelper;
//import com.groupbuying.common.baseutils.baseframework4plugins.utils.DateFormatHelper;
//import com.groupbuying.common.baseutils.baseframework4plugins.utils.JsonUtils;
//import com.groupbuying.common.service.FileRpcService;

import com.alibaba.fastjson.JSON;
import com.groupbuying.store.connector.FileFegin;
import com.groupbuying.store.connector.SysconfigFeign;
import com.groupbuying.store.connector.YsServiceFeign;
import com.groupbuying.store.constants.CommonConstants;
import com.groupbuying.store.constants.StoreMainInfoEnumConstants;
import com.groupbuying.store.dao.StoreShopDao;
import com.groupbuying.store.domain.*;
import com.groupbuying.store.dto.StorePhotoDTO;
import com.groupbuying.store.dto.StoreShopPageDTO;
import com.groupbuying.store.dto.YsPayDTO;
import com.groupbuying.store.dto.YsPayOrderBean;
import com.groupbuying.store.dto.forExternal.StoreShopDTO;
import com.groupbuying.store.dto.forExternal.do2dto.StoreShopConvert;
import com.groupbuying.store.pojo.CompanyInfoEnum;
import com.groupbuying.store.pojo.StoreShopEnum;
import com.groupbuying.store.pojo.YspayConfig;
import com.groupbuying.store.service.*;
import com.groupbuying.store.utils.*;
import com.groupbuying.store.utils.apiresult.ApiResultCode;
import com.groupbuying.store.utils.apiresult.JsonUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@Transactional
public class StoreShopServiceImpl implements StoreShopService {
    @Autowired
    private StoreShopDao storeShopDao;
    @Autowired
    private StoreCompanyInfoService storeCompanyInfoService;
    @Autowired
    private CompanyQualificationService companyQualificationService;
    @Autowired
    private StoreMainInfoService storeMainInfoService;
    @Autowired
    @Lazy
    private StoreCapitalVirtualAccountService storeCapitalVirtualAccountService;
    @Autowired
    private FileFegin fileFegin;
    @Autowired
    private YsServiceFeign ysServiceFeign;
    @Autowired
    private SysconfigFeign sysconfigFeign;
    @Autowired
    private StoreRecommendService storeRecommendService;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private StoreOpexRuleRelService storeOpexRuleRelService;

    @Value("${download.url}")
    private String downLoadUrl;

    private static Logger log = LoggerFactory.getLogger(StoreShopServiceImpl.class);


    @Override
    public StoreShopDO get(String uuid) {
        return storeShopDao.get(uuid);
    }

    @Override
    public List<StoreShopDO> list(Map<String, Object> map) {
        return storeShopDao.list(map);
    }

    @Override
    public int count(Map<String, Object> map) {
        return storeShopDao.count(map);
    }

    @Override
    public int save(StoreShopDO storeShop) {
        return storeShopDao.save(storeShop);
    }

    @Override
    public int update(StoreShopDO storeShop) {
        return storeShopDao.update(storeShop);
    }

    @Override
    public int remove(String uuid) {
        return storeShopDao.remove(uuid);
    }

    @Override
    public int batchRemove(String[] uuids) {
        return storeShopDao.batchRemove(uuids);
    }

    @Override
    public StoreShopDO getByStoreUuid(String storeUuid) {
        Map map = new HashMap();
        map.put("delflag", CommonConstants.COMMON_FLAG_UNDEL);
        map.put("storeuuid", storeUuid);
        List<StoreShopDO> list = storeShopDao.list(map);
        return list != null && list.size() > 0 ? list.get(0) : null;
    }

    @Override
    public void froozenShopByStoreUuid(String storeUuid) {
        //1.设置店铺停业
        StoreShopDO storeShop = this.getByStoreUuid(storeUuid);
        if (storeShop != null) {
            storeShop.setBusinessstate(StoreShopEnum.STOPBUSINESS);
            this.update(storeShop);
        }
    }

    @Override
    public void unfroozenShopByStoreUuid(String storeUuid) {
        //1.设置店铺营业
        StoreShopDO storeShop = this.getByStoreUuid(storeUuid);
        if (storeShop != null) {
            storeShop.setBusinessstate(StoreShopEnum.INTHEBUSINESS);
            this.update(storeShop);
        }
    }

    @Override
    public Map<String, StoreShopDO> getMapByStoreUuids(List<String> storeUuids) {
        Map<String, Object> param = new HashMap<>();
        param.put("delflag", CommonConstants.COMMON_FLAG_UNDEL);
        param.put("storeuuids", storeUuids);
        List<StoreShopDO> lsStoreShop = storeShopDao.getMapByStoreUuids(param);
        Map<String, StoreShopDO> result = new HashMap<>();
        if (lsStoreShop != null && lsStoreShop.size() > 0) {
            for (StoreShopDO storeShopDO : lsStoreShop) {
                result.put(storeShopDO.getStoreuuid(), storeShopDO);
            }
        }
        return result;
    }

    @Override
    public Map<String, Object> reportYSInfo(Map<String, Object> mapParams) {

        Object temp = mapParams.get("storeUuid");
        String storeUuid = temp != null ? temp.toString() : null;

        if (StringUtils.isBlank(storeUuid)) {
            return ReturnUtils.paramIsNull();
        }
        //商户主信息
        StoreMainInfoDO storeMainInfo = storeMainInfoService.get(storeUuid);
        //获取商户企业信息
        StoreCompanyInfoDO companyInfo = storeCompanyInfoService.getCompanyInfoByStoreUuid(storeUuid);
        CompanyQualificationDO companyQualification = null;
        if (companyInfo != null) {
            // 获取企业资质信息
            companyQualification = companyQualificationService.getQualificationByCompanyUuid(companyInfo.getUuid());
        } else {
            companyInfo = new StoreCompanyInfoDO();
            companyQualification = new CompanyQualificationDO();
        }

        StoreCapitalVirtualAccountDO virtualModel = storeCapitalVirtualAccountService.getStoreCapitalVirtualAccountByStoreUuid(storeUuid);

        Map<String, Object> result = new HashMap<>();
        result.put("storeMainInfo", storeMainInfo);
        result.put("companyInfo", companyInfo);
        result.put("companyQualification", companyQualification);
        result.put("virtualAccount", virtualModel);

        return result;
        //return  ReturnUtils.createReturnResult(ApiResultCode.SUCCESS.code(),ApiResultCode.SUCCESS.message(),true, JsonUtils.objectToJson(result));
    }

    @Override
    public Map<String, Object> reportYS(Map<String, Object> mapParams) throws Exception {

        YsPayDTO ysPayDTO = JSON.parseObject(sysconfigFeign.getYSBusiness(), YsPayDTO.class);

        Object temp = mapParams.get("storeUuid");
        String storeUuid = temp != null ? temp.toString() : null;

        if (StringUtils.isBlank(storeUuid)) {
            return ReturnUtils.paramIsNull();
        }
        //商户主信息
        StoreMainInfoDO storeMainInfo = storeMainInfoService.get(storeUuid);
        //获取商户企业信息
        StoreCompanyInfoDO companyInfo = storeCompanyInfoService.getCompanyInfoByStoreUuid(storeUuid);
        if (companyInfo == null) {
            return ReturnUtils.createReturnResult(ApiResultCode.COMPANYINFO_NOTEXISTS.code(), ApiResultCode.COMPANYINFO_NOTEXISTS.message(), false, "");
        }

        // 获取企业资质信息
        CompanyQualificationDO companyQualification = companyQualificationService.getQualificationByCompanyUuid(companyInfo.getUuid());
        if (companyQualification == null) {
            return ReturnUtils.createReturnResult(ApiResultCode.COMPANYQUALIFICATION_NOTEXISTS.code(), ApiResultCode.COMPANYQUALIFICATION_NOTEXISTS.message(), false, "");
        }
        //企业资金账户
        StoreCapitalVirtualAccountDO virtualModel = storeCapitalVirtualAccountService.getStoreCapitalVirtualAccountByStoreUuid(storeUuid);
        if (virtualModel == null) {
            return ReturnUtils.createReturnResult(ApiResultCode.STORECAPITALVIRTUALACCOUNT_NOTEXISTS.code(), ApiResultCode.STORECAPITALVIRTUALACCOUNT_NOTEXISTS.message(), false, "");
        }
        //获取组装对接信息
        //企业名称
        String companyName = companyInfo.getCompanyname();
        if (StringUtils.isBlank(companyName)) {
            return ReturnUtils.createReturnResult(ApiResultCode.PARAMNULL.code(), "企业名称为空", false, "");
        }
        //企业类型
        String companyType = companyInfo.getCompanytype();
        if (StringUtils.isBlank(companyType)) {
            return ReturnUtils.createReturnResult(ApiResultCode.PARAMNULL.code(), "企业类型为空", false, "");
        }
        //法人名称  非小微商户需要校验法人费用
        String legalPerson = companyInfo.getLegalperson();
        //是否小微
        boolean isXW = CompanyInfoEnum.COMPANYTYPE_XW.equals(companyType);
        //是否企业
        boolean isQY = CompanyInfoEnum.COMPANYTYPE_QY.equals(companyType);
        if ((!isXW) && StringUtils.isBlank(legalPerson)) {
            return ReturnUtils.createReturnResult(ApiResultCode.PARAMNULL.code(), "法人名称为空", false, "");
        }
        //法人手机号
        String legalMobile = companyInfo.getLegalmobile();
        if (StringUtils.isBlank(legalMobile)) {
            return ReturnUtils.createReturnResult(ApiResultCode.PARAMNULL.code(), "法人手机号为空", false, "");
        }
        //法人证件类型
        String documentType = companyInfo.getDocumenttype();
        if (StringUtils.isBlank(documentType)) {
            return ReturnUtils.createReturnResult(ApiResultCode.PARAMNULL.code(), "法人证件类型为空", false, "");
        }
        //法人证件编号
        String legalId = companyInfo.getLegalid();
        if (StringUtils.isBlank(legalId)) {
            return ReturnUtils.createReturnResult(ApiResultCode.PARAMNULL.code(), "法人证件编号为空", false, "");
        }
        legalId = SrcDesUtil.encryptExtraData(YsUtils.addZeroForNum(ysPayDTO.getPARTNER_ID(), 8), legalId);
        //证件有效期
        String legalIdTime = companyInfo.getLegalidtime();

        //省信息
        String provinceName = companyInfo.getProvince();
        if (StringUtils.isBlank(provinceName)) {
            return ReturnUtils.createReturnResult(ApiResultCode.PARAMNULL.code(), "企业所在省信息为空", false, "");
        }
        //市信息
        String cityName = companyInfo.getCity();
        if (StringUtils.isBlank(cityName)) {
            return ReturnUtils.createReturnResult(ApiResultCode.PARAMNULL.code(), "企业所在市信息为空", false, "");
        }
        //地址信息
        String address = companyInfo.getAddress();
        if (StringUtils.isBlank(address)) {
            return ReturnUtils.createReturnResult(ApiResultCode.PARAMNULL.code(), "企业详细地址为空", false, "");
        }
        address = address.replaceAll("\\(|\\)|（|）", "");
        //所属行业
        String saleType = companyInfo.getSaletype();
        if (StringUtils.isBlank(saleType)) {
            return ReturnUtils.createReturnResult(ApiResultCode.PARAMNULL.code(), "企业所属行业为空", false, "");
        }
        //清算方式
        String settleType = storeMainInfo.getSettletype();
        if (StringUtils.isBlank(settleType)) {
            return ReturnUtils.createReturnResult(ApiResultCode.PARAMNULL.code(), "清算方式为空", false, "");
        }
        //营业执照
        String bussinessLicense = companyQualification.getBussinesslicense();
        if ((!isXW) && StringUtils.isBlank(bussinessLicense)) {
            return ReturnUtils.createReturnResult(ApiResultCode.PARAMNULL.code(), "营业执照为空", false, "");
        }
        //营业执照有效日期
        String bussinessLicenseTime = companyQualification.getBussinesslicensetime();
        if ((!isXW) && StringUtils.isBlank(bussinessLicenseTime)) {
            return ReturnUtils.createReturnResult(ApiResultCode.PARAMNULL.code(), "营业执照有效时间为空", false, "");
        }
        //银行账户
        String companyAccountNo = virtualModel.getCompanyaccountno();
        if (StringUtils.isBlank(companyAccountNo)) {
            return ReturnUtils.createReturnResult(ApiResultCode.PARAMNULL.code(), "银行卡账号为空", false, "");
        }
        //银行开户名
        String openAccountName = virtualModel.getOpenaccountname();
        if (StringUtils.isBlank(openAccountName)) {
            return ReturnUtils.createReturnResult(ApiResultCode.PARAMNULL.code(), "银行开户名为空", false, "");
        }
        //银行卡账户类型
        String accoutType = virtualModel.getAccounttype();
        if (StringUtils.isBlank(accoutType)) {
            return ReturnUtils.createReturnResult(ApiResultCode.PARAMNULL.code(), "银行卡账户类型为空", false, "");
        }
        String bankAccoutType = "personal";
        if ("2".equals(accoutType)) {
            bankAccoutType = "corporate";
        }
        //银行开户行详细名称
        String bankName = virtualModel.getBankname();
        if (StringUtils.isBlank(bankName)) {
            return ReturnUtils.createReturnResult(ApiResultCode.PARAMNULL.code(), "银行开户行详细名称为空", false, "");
        }
        //银行开户行
        String openAccountBankName = virtualModel.getOpenaccountbankname();
        if (StringUtils.isBlank(openAccountBankName)) {
            return ReturnUtils.createReturnResult(ApiResultCode.PARAMNULL.code(), "银行开户行详细名称为空", false, "");
        }
        //银行所在省
        String bankProvinceName = virtualModel.getProvincename();
        if (StringUtils.isBlank(bankProvinceName)) {
            return ReturnUtils.createReturnResult(ApiResultCode.PARAMNULL.code(), "银行所在省为空", false, "");
        }
        //银行所在市
        String bankCityName = virtualModel.getCityname();
        if (StringUtils.isBlank(bankCityName)) {
            return ReturnUtils.createReturnResult(ApiResultCode.PARAMNULL.code(), "银行所在市为空", false, "");
        }
        //银行卡类型
        String bankCardType = virtualModel.getBankcardtype();
        if (StringUtils.isBlank(bankCardType)) {
            return ReturnUtils.createReturnResult(ApiResultCode.PARAMNULL.code(), "银行卡类型为空", false, "");
        }
        //银行卡身份证号
        String bankPeopleId = virtualModel.getPeopleid();
        if (StringUtils.isBlank(bankPeopleId)) {
            return ReturnUtils.createReturnResult(ApiResultCode.PARAMNULL.code(), "银行卡身份证号为空", false, "");
        }
        bankPeopleId = SrcDesUtil.encryptExtraData(YsUtils.addZeroForNum(ysPayDTO.getPARTNER_ID(), 8), bankPeopleId);
        //银行开户人证件类型 目前只支持00,00为身份证
        String bankCertType = virtualModel.getDocumenttype();
        if (StringUtils.isBlank(bankCertType)) {
            return ReturnUtils.createReturnResult(ApiResultCode.PARAMNULL.code(), "银行卡开户人证件类型为空", false, "");
        }
        //银行预留手机号
        String bankMobile = virtualModel.getMobile();
        if (StringUtils.isBlank(bankMobile)) {
            return ReturnUtils.createReturnResult(ApiResultCode.PARAMNULL.code(), "银行卡预留手机号为空", false, "");
        }

        //上传文件集合
        Map<String, Object> fileMap = new HashMap();
        //身份证正面照
        String fileGroupKey = companyInfo.getLegalidcard1();
        if (StringUtils.isBlank(fileGroupKey)) {
            return ReturnUtils.createReturnResult(ApiResultCode.PARAMNULL.code(), "法人身份证正面照未上传", false, "");
        }

        fileMap.put("00", fileFegin.getFileUuids(fileGroupKey).get(0));
        //身份证反面照
        fileGroupKey = companyInfo.getLegalidcard2();
        if (StringUtils.isBlank(fileGroupKey)) {
            return ReturnUtils.createReturnResult(ApiResultCode.PARAMNULL.code(), "法人身份证反面照未上传", false, "");
        }

        fileMap.put("30", fileFegin.getFileUuids(fileGroupKey).get(0));
        //结算银行卡 只有非企业类型才有
        if (!isQY) {
            //结算银行卡正面照
            fileGroupKey = companyInfo.getSettle1image();
            if (StringUtils.isBlank(fileGroupKey)) {
                return ReturnUtils.createReturnResult(ApiResultCode.PARAMNULL.code(), "结算银行卡正面照未上传", false, "");
            }
            fileMap.put("35", fileFegin.getFileUuids(fileGroupKey).get(0));
            //结算银行卡反面照
            fileGroupKey = companyInfo.getSettle2image();
            if (StringUtils.isBlank(fileGroupKey)) {
                return ReturnUtils.createReturnResult(ApiResultCode.PARAMNULL.code(), "结算银行卡反面照未上传", false, "");
            }
            fileMap.put("36", fileFegin.getFileUuids(fileGroupKey).get(0));

        } else {

            //开户许可证或印鉴卡
            fileGroupKey = companyInfo.getLicenseimage();
            if (StringUtils.isBlank(fileGroupKey)) {
                return ReturnUtils.createReturnResult(ApiResultCode.PARAMNULL.code(), "开户许可证或印鉴卡未上传", false, "");
            }
            fileMap.put("37", fileFegin.getFileUuids(fileGroupKey).get(0));
        }
        //客户协议书
        fileGroupKey = companyInfo.getAgreementimage();
        if (StringUtils.isNotBlank(fileGroupKey)) {
            fileMap.put("31", fileFegin.getFileUuids(fileGroupKey).get(0));
            //return ReturnUtils.createReturnResult(ApiResultCode.PARAMNULL.code(), "客户协议书未上传", false, "");
        }

        //营业执照
        fileGroupKey = companyQualification.getBussinesslicensephoto();
        if (!isXW) {
            if (StringUtils.isBlank(fileGroupKey)) {
                return ReturnUtils.createReturnResult(ApiResultCode.PARAMNULL.code(), "营业执照未上传", false, "");
            }
            fileMap.put("19", fileFegin.getFileUuids(fileGroupKey).get(0));
        }

        //手持身份证正扫面照
        //手持身份证正扫面照
        /*fileGroupKey = companyInfo.getLegalInHandCard();
        if (!isQY) {
            if (StringUtils.isBlank(fileGroupKey)) {
                return ReturnUtils.createReturnResult(ApiResultCode.PARAMNULL.code(), "手持身份证照片未上传", false, "");
            }
            fileMap.put("33", fileFegin.getFileUuids(fileGroupKey).get(0));
        }*/
        //String mer_outside_custid = storeMainInfo.getStoreno()+ DateFormatHelper.getNowTimeStr("yyyyMMddHHmmss");

        // 对以上信息组装为银盛参数
        YsPayOrderBean ysPayOrderBean = new YsPayOrderBean();
        ysPayOrderBean.setCust_type(companyType);
        //非小微商户设置
        if (!isXW) {
            ysPayOrderBean.setLegal_name(legalPerson);
            ysPayOrderBean.setBus_license(bussinessLicense);
            ysPayOrderBean.setBus_license_expire(DateFormatHelper.getTimeStr("yyyyMMdd", DateFormatHelper.toDate(bussinessLicenseTime, "yyyy-MM-dd")));
            ysPayOrderBean.setCust_name(companyName);
        } else {
            ysPayOrderBean.setCust_name(legalPerson);

        }
        ysPayOrderBean.setAnother_name(legalPerson);
        ysPayOrderBean.setLegal_tel(legalMobile);
        ysPayOrderBean.setLegal_cert_type(documentType);
        ysPayOrderBean.setLegal_cert_no(legalId);
        ysPayOrderBean.setLegal_cert_no_time(DateFormatHelper.getTimeStr("yyyyMMdd", DateFormatHelper.toDate(legalIdTime, "yyyy-MM-dd")));
        ysPayOrderBean.setProvince(provinceName);
        ysPayOrderBean.setCity(cityName);
        ysPayOrderBean.setCompany_addr(address);
        ysPayOrderBean.setIndustry(saleType);
        ysPayOrderBean.setSettle_type(settleType);
        ysPayOrderBean.setBank_account_no(companyAccountNo);
        ysPayOrderBean.setBank_account_name(openAccountName);
        ysPayOrderBean.setBank_account_type(bankAccoutType);
        ysPayOrderBean.setBank_name(bankName);
        ysPayOrderBean.setBank_type(openAccountBankName);
        ysPayOrderBean.setBank_province(bankProvinceName);
        ysPayOrderBean.setBank_city(bankCityName);
        ysPayOrderBean.setBank_card_type(bankCardType);
        ysPayOrderBean.setCert_no(bankPeopleId);
        ysPayOrderBean.setCert_type(bankCertType);
        ysPayOrderBean.setBank_telephone_no(bankMobile);
        ysPayOrderBean.setMer_outside_custid(storeMainInfo.getUuid());
        ysPayOrderBean.setToken("");
        //需要注意是子机构号还是主机构号
        ysPayOrderBean.setOrg_no(YspayConfig.ORG_NO);

        Map<String, Object> params = MapUtils.objectToMap(ysPayOrderBean);
        params.put("fileMap", JSONUtils.beanToJson(fileMap));
        params.put("isXW", isXW);
        params.put("isQY", isQY);

        String registryResult = ysServiceFeign.registryStore(params);
        Map<String, Object> registryResultMap = JSONUtils.jsonToMap(registryResult);
        String msg = registryResultMap.get("msg").toString();


        return ReturnUtils.createReturnResult(ApiResultCode.OPRSUCCESS.code(), msg, true, "");

    }

    @Override
    public R getShopList(Map<String, Object> params) {
        Object temp = params.get("longitude");
        Double longitude = temp != null ? Double.parseDouble(temp.toString()) : null;
        temp = params.get("latitude");
        Double latitude = temp != null ? Double.parseDouble(temp.toString()) : null;
        // 每页显示的条数
        temp = params.get("pageShow");
        Integer pageShow = temp != null ? Integer.parseInt(temp.toString()) : null;

        temp = params.get("level");
        Integer level = temp != null ? Integer.parseInt(temp.toString()) : null;

        if (longitude == null || latitude == null || pageShow == null || pageShow == 0 || level == null) {
            return R.error("params is null");
        }

        //获取
        String geoCode = GeoHashUtils.getGeoHash(latitude, longitude, level);
        String[] geoCodes = GeoHashUtils.getAdjacent(latitude, longitude, level);
        Map<String, Object> map = new HashMap<>();
        for (int i = 0; i < geoCodes.length; i++) {
            map.put("geoCode" + (i + 1), geoCodes[i]);
        }
        map.put("geoCode9", geoCode);
        map.put("level", level);

        List<StoreShopDO> queryList = storeShopDao.queryListByGeoHash(map);

        if (!(queryList.size() > 0)) {
            return R.data(new StoreShopPageDTO(0, 0, pageShow, new ArrayList<>()));
        }

        //保存距离 修改图片地址
        List<Map<String, Object>> shopList = new ArrayList<>();
        dealStoreData(longitude, latitude, queryList, shopList);
        //分页
        return R.data(getPagedList(shopList, pageShow));
    }

    @Override
    public Object searchShopListByCategoryOrStoreName(Map<String, Object> params) {
        Object temp = params.get("longitude");
        Double longitude = temp != null ? Double.parseDouble(temp.toString()) : null;
        temp = params.get("latitude");
        Double latitude = temp != null ? Double.parseDouble(temp.toString()) : null;
        // 每页显示的条数
        temp = params.get("pageShow");
        Integer pageShow = temp != null ? Integer.parseInt(temp.toString()) : null;
        // 品类名称
        temp = params.get("categoryName");
        String categoryName = temp != null ? temp.toString() : null;
        // 部分品类名称 用于模糊匹配
        temp = params.get("categoryNamePart");
        String categoryNamePart = temp != null ? temp.toString() : null;
        // 商户名称
        temp = params.get("storeName");
        String storeName = temp != null ? temp.toString() : null;
        // 商户名称
        temp = params.get("storeNameOrCategoryNamePart");
        String storeNameOrCategoryNamePart = temp != null ? temp.toString() : null;

        if ( pageShow == null || pageShow == 0) {
            return R.error("params is null");
        }

        //获取
        Map map = new HashMap();
        map.put("categoryName", categoryName);
        map.put("storeName", storeName);
        map.put("categoryNamePart", categoryNamePart);
        map.put("storeNameOrCategoryNamePart", storeNameOrCategoryNamePart);
        //获取商家数据
        List<StoreShopDO> queryList = storeShopDao.searchShopListByCategoryOrStoreName(map);

        if (!(queryList.size() > 0)) {
            return R.data(new StoreShopPageDTO(0, 0, pageShow, new ArrayList<>()));
        }

        //保存距离 修改图片地址
        List<Map<String, Object>> shopList = new ArrayList<>();
        dealStoreData(longitude, latitude, queryList, shopList);
        //分页
        return R.data(getPagedList(shopList, pageShow));
    }

    @Override
    public Object getRecommendStoreList(Map<String, Object> params) {


        Object temp = params.get("longitude");
        Double longitude = temp != null ? Double.parseDouble(temp.toString()) : null;
        temp = params.get("latitude");
        Double latitude = temp != null ? Double.parseDouble(temp.toString()) : null;

        // 有缓存
        Object redisData = redisUtils.getValue("store_recommend");
        if (redisData != null) {
            List<Map<String, Object>> list = (List<Map<String, Object>>) JsonUtils.convertBean(redisData.toString(), List.class);
            //只处理距离和排序
            dealStoreData(longitude, latitude, list);
            return R.data(list);
        }


        //获取商家数据
        List<StoreShopDO> queryList = storeShopDao.getRecommendStoreList(params);
        if (!(queryList.size() > 0)) {
            return R.data(new ArrayList<>());
        }
        //保存距离 修改图片地址
        List<Map<String, Object>> shopList = new ArrayList<>();
        dealStoreDataAndScore(longitude, latitude, queryList, shopList);

        redisUtils.setKey("store_recommend", JsonUtils.beanToJson(shopList), 60 * 60 * 24);

        //分页
        return R.data(shopList);
    }

    public void getOpexRule(Map<String, Object> shop, String storeUuid) {
        String ruleId = storeOpexRuleRelService.getOpexRuleByStoreID(storeUuid);

        Map ruleMap = new HashMap();
        ruleMap.put("ruleId", ruleId);
        ruleMap.put("delFlag", CommonConstants.COMMON_FLAG_UNDEL);
        Map ruleRes = sysconfigFeign.getStoreOpexRule(ruleMap);
        if (ruleRes != null) {
            BigDecimal backCurrency = new BigDecimal(ruleRes.get("backCurrencyRatio").toString());
            BigDecimal discount = new BigDecimal(ruleRes.get("currencyPayDiscount").toString());
            discount = discount.divide(new BigDecimal(10));
            shop.put("ratio", backCurrency);
            shop.put("discount", discount);
            shop.put("ruleId", ruleId);
        }
    }

    public void dealStoreDataAndScore(Double longitude, Double latitude, List<StoreShopDO> storeShopList, List<Map<String, Object>> shopList) {
        Map<String, Object> shopMap;
        Map<String, Object> queryParam = new HashMap<>();
        if (longitude == null || latitude == null) {
            for (StoreShopDO storeShop : storeShopList) {


                StorePhotoDTO storePhotoDTO = new StorePhotoDTO();
                storePhotoDTO.setSlideshow(fileFegin.getDownloadUrlByFileGroupKey(storeShop.getSlideshow()));
                storePhotoDTO.setDoorPhoto(fileFegin.getDownloadUrlByFileGroupKey(storeShop.getDoorphoto()));
                storePhotoDTO.setWithinPhoto(fileFegin.getDownloadUrlByFileGroupKey(storeShop.getWithinphoto()));
                shopMap = new HashMap<>();
                shopMap.put("shop", StoreShopConvert.MAPPER.doToDTO(storeShop));
                shopMap.put("distance",">5km");
                shopMap.put("photo", storePhotoDTO);

                queryParam.put("storeuuid", storeShop.getStoreuuid());
                StoreRecommendDO storeRecommendDO = storeRecommendService.list(queryParam).get(0);
                shopMap.put("score",storeRecommendDO.getScore());
                //商户积分规则
                getOpexRule(shopMap, storeShop.getStoreuuid());
                shopList.add(shopMap);
            }
        }else {
            for (StoreShopDO storeShop : storeShopList) {

                StorePhotoDTO storePhotoDTO = new StorePhotoDTO();
                storePhotoDTO.setSlideshow(fileFegin.getDownloadUrlByFileGroupKey(storeShop.getSlideshow()));
                storePhotoDTO.setDoorPhoto(fileFegin.getDownloadUrlByFileGroupKey(storeShop.getDoorphoto()));
                storePhotoDTO.setWithinPhoto(fileFegin.getDownloadUrlByFileGroupKey(storeShop.getWithinphoto()));
                shopMap = new HashMap<>();
                shopMap.put("shop", StoreShopConvert.MAPPER.doToDTO(storeShop));
                shopMap.put("distance", new Double(DistanceUtils.getDistance(longitude, latitude, storeShop.getLgt().doubleValue(), storeShop.getLat().doubleValue())).toString());
                shopMap.put("photo", storePhotoDTO);

                queryParam.put("storeuuid", storeShop.getStoreuuid());
                StoreRecommendDO storeRecommendDO = storeRecommendService.list(queryParam).get(0);
                shopMap.put("score",storeRecommendDO.getScore());
                //商户积分规则
                getOpexRule(shopMap, storeShop.getStoreuuid());
                shopList.add(shopMap);
            }

        }


    }

    public void dealStoreData(Double longitude, Double latitude, List<StoreShopDO> storeShopList, List<Map<String, Object>> shopList) {
        Map<String, Object> shopMap;
        if (longitude == null || latitude == null) {
            for (StoreShopDO storeShop : storeShopList) {

                StorePhotoDTO storePhotoDTO = new StorePhotoDTO();
                storePhotoDTO.setSlideshow(fileFegin.getDownloadUrlByFileGroupKey(storeShop.getSlideshow()));
                storePhotoDTO.setDoorPhoto(fileFegin.getDownloadUrlByFileGroupKey(storeShop.getDoorphoto()));
                storePhotoDTO.setWithinPhoto(fileFegin.getDownloadUrlByFileGroupKey(storeShop.getWithinphoto()));
                shopMap = new HashMap<>();
                shopMap.put("shop", StoreShopConvert.MAPPER.doToDTO(storeShop));
                shopMap.put("distance",">5km");
                shopMap.put("photo", storePhotoDTO);
                shopMap.put("score","5");
                //商户积分规则
                getOpexRule(shopMap, storeShop.getStoreuuid());
                shopList.add(shopMap);
            }
        }else {
            for (StoreShopDO storeShop : storeShopList) {

                StorePhotoDTO storePhotoDTO = new StorePhotoDTO();
                storePhotoDTO.setSlideshow(fileFegin.getDownloadUrlByFileGroupKey(storeShop.getSlideshow()));
                storePhotoDTO.setDoorPhoto(fileFegin.getDownloadUrlByFileGroupKey(storeShop.getDoorphoto()));
                storePhotoDTO.setWithinPhoto(fileFegin.getDownloadUrlByFileGroupKey(storeShop.getWithinphoto()));
                shopMap = new HashMap<>();
                shopMap.put("shop", StoreShopConvert.MAPPER.doToDTO(storeShop));
                shopMap.put("distance", new Double(DistanceUtils.getDistance(longitude, latitude, storeShop.getLgt().doubleValue(), storeShop.getLat().doubleValue())).toString());
                shopMap.put("photo", storePhotoDTO);
                shopMap.put("score","5");
                //商户积分规则
                getOpexRule(shopMap, storeShop.getStoreuuid());
                shopList.add(shopMap);
            }
            //排序
            storeSort(shopList);

        }


    }

    public void dealStoreData(Double longitude, Double latitude, List<Map<String, Object>> shopList) {

        Map<String, Object> param = new HashMap();
        param.put("isDelete", CommonConstants.COMMON_FLAG_UNDEL);
        if (longitude == null || latitude == null) {
            for (Map<String, Object> storeShop : shopList) {
                String shopStr = JsonUtils.beanToJson(storeShop.get("shop"));
                StoreShopDTO storeShopDTO = JsonUtils.convertBean(shopStr, StoreShopDTO.class);
                storeShop.put("distance",">5km");

                //获取积分规则
                getOpexRule(storeShop, storeShopDTO.getStoreUuid());

                param.put("storeuuid", storeShopDTO.getStoreUuid());
                StoreRecommendDO storeRecommendDO = storeRecommendService.list(param).get(0);
                storeShop.put("score", storeRecommendDO.getScore());
            }

        } else {

            for (Map<String, Object> storeShop : shopList) {

                String shopStr = JsonUtils.beanToJson(storeShop.get("shop"));
                StoreShopDTO storeShopDTO = JsonUtils.convertBean(shopStr, StoreShopDTO.class);
                storeShop.put("distance", new Double(DistanceUtils.getDistance(longitude, latitude, storeShopDTO.getLongitude().doubleValue(), storeShopDTO.getLatitude().doubleValue())).toString());
                //获取积分规则
                getOpexRule(storeShop, storeShopDTO.getStoreUuid());

                param.put("storeuuid", storeShopDTO.getStoreUuid());
                StoreRecommendDO storeRecommendDO = storeRecommendService.list(param).get(0);
                storeShop.put("score", storeRecommendDO.getScore());
            }

        }
    }


    public void storeSort(List<Map<String, Object>> shopList) {
        Map<String, Object> shopMap;
        for (int i = shopList.size() - 1; i > 0; i--) {
            boolean flag = true;
            for (int j = 0; j < i; j++) {
                double distanceA = Double.parseDouble(shopList.get(j).get("distance").toString());
                double distanceB = Double.parseDouble(shopList.get(j + 1).get("distance").toString());
                if (distanceA > distanceB) {
                    shopMap = shopList.get(j);
                    shopList.set(j, shopList.get(j + 1));
                    shopList.set(j + 1, shopMap);
                    flag = false;
                }
            }
            if (flag) {
                break;
            }
        }
    }


    private StoreShopPageDTO getPagedList(List<Map<String, Object>> data, int pageShow) {
        int dataSize = data.size();
        int pageTotal = Double.valueOf(Math.ceil((double) dataSize / (double) pageShow)).intValue();
        List<List<Map<String, Object>>> pageData = new ArrayList();
        for (int pageNum = 0; pageNum < pageTotal; pageNum++) {

            int fromIndex = pageNum * pageShow;
            if (fromIndex >= dataSize) {
                return null;
            }

            int toIndex = (pageNum + 1) * pageShow;
            if (toIndex >= data.size()) {
                toIndex = data.size();
            }
            pageData.add(data.subList(fromIndex, toIndex));
        }
        StoreShopPageDTO dto = new StoreShopPageDTO(dataSize, pageTotal, pageShow, pageData);
        return dto;
    }

}
